package com.handler.filter;

import org.apache.commons.lang.StringEscapeUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {


  /**
   * Constructs a request object wrapping the given request.
   *
   * @param request
   * @throws IllegalArgumentException if the request is null
   */
  public XssHttpServletRequestWrapper(HttpServletRequest request) {
    super(request);
  }

  @Override
  public String getParameter(String name) {
    if ("logo".equals(name) || "url".equals(name) || "simContent".equals(name)) {
      return super.getParameter(name);
    }
    return escape(super.getParameter(name));
  }

  @Override
  public String[] getParameterValues(String name) {
    String[] values = super.getParameterValues(name);
    if (values == null) {
      return null;
    }
    if ("logo".equals(name) || "url".equals(name) || "simContent".equals(name)) {
      return values;
    }
    String[] escapedValues = new String[values.length];
    for (int i = 0; i < values.length; i++) {
      escapedValues[i] = escape(values[i]);
    }
    return escapedValues;
  }

  private String escape(String source) {
    if (source == null) {
      return null;
    }
    source = source.replace("<","&lt;");
    source = source.replace(">","&gt;");
    return source;
  }

}
